var Registration = {
		
		REGISTRATION_URL : "/company/pages/user",
		
		validateEmail : function validate(email) {
			var pattern = /^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}$/;
			return pattern.test(email);
		},
		
		validateForm : function validate() {
			
			var validFlag = true;
			
			if ($('#username').val() == '') {
				$('#login-error').html($('#username-required-error').html());
				validFlag = false;
			} else {
				if ($('#username').val().length < 3) {
					$('#login-error').html($('#username-short-error').html());
					validFlag = false;
				}
			}
			
			if ($('#email').val() == '') {
				$('#email-error').html($('#email-required-error').html());
				validFlag = false;
			} else {
				if (!(Registration.validateEmail($('#email').val()))) {
					$('#email-error').html($('#email-wrong-error').html());
					validFlag = false;
				}
			}
			
			if ($('#password').val() == '') {
				$('#password-error').html($('#password-required-error').html());
				validFlag = false;
			} else {
				if ($('#password').val().length < 6) {
					$('#password-error').html($('#password-short-error').html());
					validFlag = false;
				}
			}
			
			if (!($('#password').val() === $('#conf-password').val())) {
				$('#form-error').html($('#password-match-error').html());
				validFlag = false;
			}
			
			return validFlag;
		},
		
		userRegistration : function register() {
			jQuery.ajax({
				type : "POST",
				async : true,
				cashe : false,
				url: Registration.REGISTRATION_URL,
				data : $('#contentbody form').serialize(),
				beforeSend : function() {
					$('#load').css({
						'display' : 'table-cell'
					});
				},
				complete : function() {
					$('#load').css({
						'display' : 'none'
					});
				},
				success : function(data) {
					var reply = jQuery.parseJSON(data);
					if (reply.isValid) {
						window.location = "/company/pages/users";
					} else {
						if (!(reply.loginError === undefined)) {
							$('#login-error').html(reply.loginError);
						}
						if (!(reply.emailError === undefined)) {
							$('#email-error').html(reply.emailError);
						}
						if (!(reply.passwordError === undefined)) {
							$('#password-error').html(reply.passwordError);
						}
						var errors = reply.errors;
						if (errors.length != 0) {
							for (var i = 0; i < errors.length; i++) {
								$('#form-error').append(errors[i] + '<br>');
							}
						}
					}				
				},
				error : function() {
					alert("error!");
				}
			});
		}
};

$(document).ready(function() {

	$("#submit").click(function() {
		$('#contentbody').find('.error').html('');
		var valid = Registration.validateForm();
		if (valid) {		
			Registration.userRegistration()
		}
		return false;
	});

});